package chapter13.section4;

//程序13-4：一个实现了二进制大数据对象的存取程序

import java.io.*;
import java.sql.*;

public class StreamType {
    // 将指定文件的内容存入数据表tb_javabook中
    public static void insert(Statement stmt, String chaper, String fileName) throws SQLException, FileNotFoundException {
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(fileName));
        // 使用特殊检索条件获得一个没有记录的ResultSet对象，以便插入记录
        ResultSet rs = stmt.executeQuery("select chapter,content" + " from tb_javabook where chapter is null");
        rs.moveToInsertRow();// 定位到插入行
        rs.updateString("chapter", chaper);
        // 数据表中的大二进制字段的Java类型是Blob，故用updateBlob()
        rs.updateBlob("content", in);
        rs.insertRow();
        rs.close();
    }

    // 将大二进制字段的内容读出并存储到指定的文件中
    public static void readToFile(Statement stmt, String chaper, String newFileName) throws SQLException, IOException {
        ResultSet rs = stmt.executeQuery("select chapter,content " + "from tb_javabook where chapter='" + chaper + "'");
        if (rs.next()) {
            // rs.getBinaryStream方法可以获得指定大二进制字段的内容
            BufferedInputStream in = new BufferedInputStream(rs.getBinaryStream("content"));
            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(newFileName));
            byte[] info = new byte[1024];
            while (in.read(info) != -1) {
                out.write(info);
            }
            in.close();
            out.close();
        }
        rs.close();
    }

    public static void main(String[] args) {
        String url = " jdbc:mysql://localhost:3306/bank?user=root&password =123456 ";
        Connection con = null;
        try {
            con = DriverManager.getConnection(url);
            // 创建一个可更新和滚动的结果集类型
            Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
            insert(stmt, "第13章", "G:/第13章-数据库.doc");
            readToFile(stmt, "第13章", "g:/new13.doc");
            stmt.close();
            con.close();
        } catch (SQLException | IOException e) {
            e.printStackTrace();
        }
    }
}
